package logic

import (
	"common/model"
	"context"
	"errors"
	product "product_server/proto"
	"time"
)

func (p *ProductServer) QueryBargainProgress(ctx context.Context, req *product.QueryBargainProgressRequest) (*product.QueryBargainProgressResponse, error) {
	orderBargain, err := model.GetOrderBargainInfo(req.OrderId)
	if err != nil || orderBargain == nil {
		return nil, errors.New("砍价订单不存在")
	}

	activity, err := model.GteBargainActivity(orderBargain.ActivityId, 0)
	if err != nil || activity == nil {
		return nil, errors.New("砍价活动不存在")
	}

	// 查询所有砍价记录
	records, err := model.GetBargainRecord(req.OrderId)
	if err != nil {
		return nil, errors.New("查询砍价记录失败")
	}

	// 组装砍价明细
	var cutDetails []*product.BargainCutDetail
	for _, rec := range records {
		cutDetails = append(cutDetails, &product.BargainCutDetail{
			UserId:    rec.UserId,
			UserType:  rec.UserType,
			CutAmount: rec.CutAmount,
			CreatedAt: rec.CreatedAt.Format(time.RFC3339),
		})
	}

	resp := &product.QueryBargainProgressResponse{
		OrderId:       orderBargain.OrderId,
		ActivityId:    orderBargain.ActivityId,
		ProductId:     activity.ProductId,
		OriginalPrice: activity.OriginalPrice,
		CurrentPrice:  orderBargain.CurrentPrice,
		TargetPrice:   activity.TargetPrice,
		TotalCuts:     activity.TotalCuts,
		CurrentCuts:   orderBargain.CurrentCuts,
		Status:        orderBargain.Status,
		ExpireTime:    orderBargain.ExpireTime.Format(time.RFC3339),
		CutDetails:    cutDetails,
	}
	return resp, nil
}
